﻿package com.fox2d 
{
	import com.fox2d.events.GameKeyEvent;
	import flash.display.Stage;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import flash.utils.Dictionary;
	
	/**
	 * ...
	 * @author Orlando Leite
	 */
	public class GameController extends EventDispatcher
	{
		private static var instance:GameController;
		
		private var gameKeyList:Dictionary = new Dictionary();
		
		private var codeGameRef:Dictionary = new Dictionary();
		private var gameCodeRef:Dictionary = new Dictionary();
		
		public function GameController( enforcer:SingletonEnforcer, stage:Stage )
		{
			if ( enforcer == null )
				throw new Error( "Only can exist one instance of GameController" );
				
			stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandle );
			stage.addEventListener( KeyboardEvent.KEY_UP, keyUpHandle );
		}
		
		public static function controller( stage:Stage = null ):GameController
		{
			if ( instance == null )
			{
				if ( stage == null )
				{
					throw new Error( "Stage should be non null at first call" );
				}
				else
				{
					instance = new GameController( new SingletonEnforcer(), stage );
				}
			}
			
			return instance;
		}
		
		public function getKeyCode( gameKey:String ):uint
		{
			return gameCodeRef[gameKey];
		}
		
		public function getKeyState( gameKey:String ):Boolean
		{
			return gameKeyList[gameKey];
		}
		
		public function addKey( gameKey:String, key:uint ):void
		{
			codeGameRef[key] = gameKey;
			gameCodeRef[gameKey] = key;
			gameKeyList[gameKey] = false;
		}
		
		public function removeKey( gameKey:String ):void
		{
			codeGameRef[gameCodeRef[gameKey]] = null;
			gameCodeRef[gameKey] = null;
			gameKeyList[gameKey] = null;
		}
		
		private function keyDownHandle( event:KeyboardEvent ):void
		{
			var temp:String = codeGameRef[event.keyCode];
			
			if ( temp && !gameKeyList[temp] )
			{
				gameKeyList[temp] = true;
				dispatchEvent( new GameKeyEvent( GameKeyEvent.BTN_DOWN, temp ) );
			}
		}
		
		private function keyUpHandle( event:KeyboardEvent ):void
		{
			var temp:String = codeGameRef[event.keyCode];
			
			if ( temp )
			{
				gameKeyList[temp] = false;
				dispatchEvent( new GameKeyEvent( GameKeyEvent.BTN_UP, temp ) );
			}
		}
		
	}
	
}

class SingletonEnforcer { };
